import { WorkflowParam, WorkflowTemplate } from '../types/workflow'
import { logger } from '../services/logger'

// 生成工作流模板
export const generateTemplate = (workflow: any): WorkflowTemplate => {
    try {
        const params = extractParams(workflow)
        const groups = groupParams(params)

        return {
            version: '1.0',
            layout: {
                type: 'form',
                groups
            },
            params
        }
    } catch (error) {
        logger.error('Error generating template:', error)
        throw error
    }
}

// 从工作流配置中提取参数
const extractParams = (workflow: any): WorkflowParam[] => {
    const params: WorkflowParam[] = []
    const nodes = workflow.nodes || []

    for (const node of nodes) {
        if (node.inputs) {
            for (const [key, value] of Object.entries(node.inputs)) {
                const param = createParam(key, value, node)
                if (param) {
                    params.push(param)
                }
            }
        }
    }

    return params
}

// 创建参数配置
const createParam = (key: string, value: any, node: any): WorkflowParam | null => {
    try {
        return {
            id: `${node.id}_${key}`,
            name: key,
            label: key.split('_').map(capitalize).join(' '),
            type: inferType(value),
            nodeId: node.id,
            component: inferComponent(value),
            required: true,
            default: value,
            ...inferAdditionalProps(value)
        }
    } catch (error) {
        logger.error('Error creating param:', { error, key, node })
        return null
    }
}

// 推断参数类型
const inferType = (value: any): string => {
    if (typeof value === 'number') return 'number'
    if (typeof value === 'boolean') return 'boolean'
    if (Array.isArray(value)) return 'array'
    if (value && typeof value === 'object') return 'object'
    return 'string'
}

// 推断组件类型
const inferComponent = (value: any): string => {
    const type = inferType(value)
    switch (type) {
        case 'number': return 'InputNumber'
        case 'boolean': return 'Switch'
        case 'array': return 'Select'
        case 'object': return 'JsonEditor'
        default: return 'Input'
    }
}

// 推断额外属性
const inferAdditionalProps = (value: any): Partial<WorkflowParam> => {
    const type = inferType(value)
    switch (type) {
        case 'number':
            return {
                min: 0,
                max: 100,
                step: 1
            }
        case 'array':
            return {
                options: Array.isArray(value) ? value : []
            }
        default:
            return {}
    }
}

// 将参数分组
const groupParams = (params: WorkflowParam[]): { title: string; fields: string[] }[] => {
    const groups = new Map<string, string[]>()

    for (const param of params) {
        const groupName = param.nodeId
        if (!groups.has(groupName)) {
            groups.set(groupName, [])
        }
        groups.get(groupName)!.push(param.id)
    }

    return Array.from(groups.entries()).map(([title, fields]) => ({
        title,
        fields
    }))
}

// 首字母大写
const capitalize = (str: string): string => {
    return str.charAt(0).toUpperCase() + str.slice(1).toLowerCase()
} 